package com.edu.base.rest.service.impl;

import com.alibaba.fastjson.JSONException;
import com.edu.base.common.sms.RegisterUtil;
import com.edu.base.rest.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.ws.http.HTTPException;
import java.util.concurrent.TimeUnit;


@Service
@Transactional
public class AdminServiceImpl implements AdminService {


  @Autowired
  private RedisTemplate<String, String> redisTemplate;

  @Value("${tencent.message.appID}")
  private String appid;

  @Value("${tencent.message.appKEY}")
  private String appkey;

  @Value("${tencent.message.templateID}")
  private int templateID;


  @Override
  public Integer getPhoneCode(String phone) {
    String verificationCode = RegisterUtil.verificationCode();
    try {
      //			SmsSingleSender ssender = new SmsSingleSender(Integer.valueOf(appid), appkey);
      //			String[] params = {verificationCode};
      //			SmsSingleSenderResult result = ssender.sendWithParam("86", phone,templateID, params, "", "", "");
      //			JSONObject resultJSON = JSON.parseObject(result.toString());
      //Integer resultMessage = (Integer) resultJSON.get("result");
      Integer resultMessage = 0;
      if (resultMessage == 0) {
        /**
         *验证码存入redis中300秒
         *这里之所以用手机号作为健是防止同一个手机号在300秒内获取第二次验证码时出现资源多余的占用
         *在有效期内再次获取验证码直接将前一次获取的验证码替换即可
         **/
        redisTemplate.opsForValue().set(phone, verificationCode, 300, TimeUnit.SECONDS);
        return 1;//已成功发送验证码到:"+phone+",请注意查收！
      } else if (resultMessage == 1016) {
        return 2;//手机号格式错误
      } else if (resultMessage == 1023) {
        return 3;//该手机号多次请求验证码，请30秒后再试！
      } else if (resultMessage == 1024) {
        return 4;//该手机号多次请求验证码，请1小时后再试！
      }
    } catch (HTTPException e) {
      return 5;// HTTP 响应码错误	e.printStackTrace();
    } catch (JSONException e) {
      return 6;// JSON 解析错误	e.printStackTrace();
    } catch (Exception e) {
      return 8;//未知错误！, 验证码发送失败！
    }
    return 1;

  }

  @Override
  public Integer register(String username, String phoneCode) {
    try {
      String redisCode = redisTemplate.opsForValue().get(username);
      //logger.info("redisCode==="+redisCode+"==========="+redisCode.equals(phoneCode));
      redisCode.equals(phoneCode);
      phoneCode.equals(redisCode);
      if (!redisCode.equals(phoneCode) || !phoneCode.equals(redisCode)) {
        return 2;//接受的验证码与redis中的验证码或手机号不匹配
      }
      return 1;
    } catch (Exception e) {
      return 2;//接受的验证码与redis中的验证码或手机号不匹配       或者    为空抛出异常时进行捕获
    }
  }


}
